import React, {Component} from 'react';
import {Button, Spin} from 'antd';
import '../css/register.css';
import {Search,Head} from '../components/EditComponent';
import app from '../AppMethod';
import {wechat, user} from "../value";
import {config} from '../config';

class Register extends Component {
    constructor(props) {
        super(props);
        this.state = {
            employee: {
                employee_name: '',
                employee_phone: '',
                employee_department: ''
            },
            loading: false
        }
    };

    render() {
        return (
            <div className="registerContainer" style={{height: '100%'}}>
                <div>
                    {/*<Search type="员工手机号码" handleSearchData={(value) => this.handleSearch(value)}/>*/}
                    <Head back="false" type="员工手机号码" handleSearchData={(value)=>this.handleSearch(value)} click={() => this.handleBack()}/>
                </div>
                <Spin spinning={this.state.loading}>
                    <div className="employeeContent">
                        <div className="employeeName">员工名：{this.state.employee.employee_name}</div>
                        <div className="employeeName">手机号：{this.state.employee.employee_phone}</div>
                        <div className="employeeName">部门：{this.state.employee.employee_department}</div>
                    </div>
                </Spin>
                <div style={{position: 'absolute', bottom: '10px', width: '100%'}}>
                    <Button type='primary' style={{width: '96%', marginLeft: '2%', height: '45px', fontSize: '18px'}}
                            onClick={() => this.handleBind()}>确认绑定</Button>
                </div>
            </div>
        )
    };

    /**
     * 初始化时根据查询结果判断用户是否被绑定，如果是则直接跳转到配送页面，如果否则通过手机号查询用户信息然后绑定跳转
     * @returns {Promise.<void>}
     */
    async componentDidMount() {
        const _this = this;
        let code = app.getQueryString('code');
        if (code == undefined || code == null || code.length <= 0) {
            await this.handleGetOpenid();
        } else {
            let result = await app.post(wechat.GET_USERINF, {code: code});
            if (result.code === 1) {
                let data = result.data;
                app.setData("openid", data.openid);
                app.setData("nickname", data.nickname);
                app.setData("headimgurl", data.headimgurl);
                app.post(user.SEARCH_USERIFBIND, {openid: data.openid}).then((result1) => {
                    if (result1.code === 1) {
                        app.setData('employee_id', result1.data.employee_id);
                        _this.props.history.push(config.path + '/operation');
                    } else {
                        app.alert("请先绑定员工", 'error', 3);
                    }
                })
            } else {
                if (app.getData("openid")) {
                    app.post(user.SEARCH_USERIFBIND, {openid: app.getData("openid")}).then((result1) => {
                        if (result1.code === 1) {
                            app.setData('employee_id', result1.data.employee_id);
                            _this.props.history.push(config.path + '/operation');
                        } else {
                            app.alert("请先绑定员工", 'error', 3);
                        }
                    })
                } else {
                    app.alert(result.msg, 'error', 3);
                }
            }

        }
    };

    /**
     * 用户授权获取code
     * @returns {Promise.<void>}
     */
    async handleGetOpenid() {
        let result = await app.post(wechat.GET_AUTHORIZEURL, {url: window.location.href.split("#")[0]})
        if (result.code === 1) {
            let url = result.data.url;
            window.location = url;
        } else {
            this.props.history.push();
            app.alert(result.msg, 'error', 3);
        }

    };

    /**
     * 根据电话号码查询的结果绑定用户
     */
    handleBind() {
        const _this = this;
        let openid = app.getData('openid');
        let nickname = app.getData('nickname');
        let headimgurl = app.getData('headimgurl');
        let employee_id = app.getData('employee_id');
        this.setState({loading: true});
        app.post(user.BIND_EMPLOYEE, {
            openid: openid,
            nickname: nickname,
            headimgurl: headimgurl,
            employee_id: employee_id
        }).then((result) => {
            if (result.code === 1) {
                app.alert('绑定成功', 'success', 3);
                this.setState({loading: false});
                _this.props.history.push(config.path + '/operation');
            } else {
                this.setState({loading: false});
                app.alert(result.msg, 'error', 6);
            }
        });

    };

    /**
     * 处理输入框查询事件
     * @param value
     */
    handleSearch(value) {
        this.setState({loading: true});
        app.post(user.QUERY_EMPLOYEEBYPHONE, {employee_phone: value}).then((result) => {
            if (result.code === 1) {
                app.setData('employee_id', result.data.employee_id);
                let employee = {};
                employee.employee_name = result.data.employee_name;
                employee.employee_phone = result.data.employee_phone;
                employee.employee_department = result.data.employee_department;
                this.setState({employee, loading: false});
            } else {
                app.alert(result.msg, 'error', 3);
                this.setState({employee: {}, loading: false});
            }
        })
    };

    /**
     * 处理返回事件
     */
    handleBack() {
        this.props.history.goBack();
    };
}

export default Register;